package it.ricettario;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Enumeration;

import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.plaf.basic.BasicSplitPaneUI;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

//SplitPaneDemo itself is not a visible component.
public class RicettarioViewer extends JPanel implements MouseListener, MouseWheelListener {

	private static final long serialVersionUID = 1L;
	
	public void mouseWheelMoved(MouseWheelEvent arg0) {
		System.out.println(arg0.getWheelRotation());
		TreePath path = tree.getSelectionPath();
		if (path != null)
		{
			Object[] paths = path.getPath();
			File file = ((NodeBean) ((javax.swing.tree.DefaultMutableTreeNode) paths[paths.length - 1]).getUserObject()).getFile();
			System.out.println("File name = " + file.getName());
			if (!file.isDirectory())
				updateLabel(file.getPath(), true, true, arg0.getWheelRotation());
		}
		
	}

	public void mouseClicked(MouseEvent arg0) {
		System.out.println("MOUSE CLICKED");
		System.out.println("Bottone:"+arg0.getButton());
		// Mouse cliccato sull'immagine
		if (arg0.getComponent() instanceof JLabel)
		{
			TreePath path = tree.getSelectionPath();
			if (path != null)
			{
				Object[] paths = path.getPath();
				File file = ((NodeBean) ((javax.swing.tree.DefaultMutableTreeNode) paths[paths.length - 1]).getUserObject()).getFile();
				System.out.println("File name = " + file.getName());
				if (!file.isDirectory())
				{
					// Fullscreen
					if (arg0.getButton() == 1)
						updateLabel(file.getPath(), false, false);
					// RESIZED
					if (arg0.getButton() == 3)
						updateLabel(file.getPath(), false, true);
				}
				else
					updateLabel(null, true, false);
			}
		}

	}

	public void mouseEntered(MouseEvent arg0) {
		System.out.println("MOUSE ENTERED");

	}

	public void mouseExited(MouseEvent arg0) {
		System.out.println("MOUSE EXITED");

	}

	public void mousePressed(MouseEvent e) {
		System.out.println("MOUSE PRESSED");
		// Immagine selezionata dall'albero
		if (e.getComponent() instanceof JTree)
		{
			int selRow = tree.getRowForLocation(e.getX(), e.getY());
			TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
			if (selRow != -1) 
				showImageFromTree(selPath);
		}

	}

	public void mouseReleased(MouseEvent arg0) {

	}
	
	public Dimension calculateImageSpace()
	{
		int width = splitPane.getWidth() - splitPane.getDividerLocation() - splitPane.getDividerSize() - pictureScrollPane.getVerticalScrollBar().getWidth();
		int height = splitPane.getHeight() - pictureScrollPane.getHorizontalScrollBar().getHeight();
		return new Dimension(width, height);
	}

	private JLabel picture;
	private JSplitPane splitPane;

	private DefaultMutableTreeNode rootNode;
	private DefaultTreeModel treeModel;
	private JTree tree;
	private static final String RICETTE_DIR = "./Ricette";
	private JScrollPane pictureScrollPane;

	public RicettarioViewer() {

		// Create the list of images and put it in a scroll pane.
		rootNode = new DefaultMutableTreeNode("Ricette");
		treeModel = new DefaultTreeModel(rootNode);
		loadTree();
		tree = new JTree(treeModel);
		tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
		tree.setShowsRootHandles(true);
		tree.setEditable(false);
		tree.setAutoscrolls(true);
		tree.addMouseListener(this);

		JScrollPane listScrollPane = new JScrollPane(tree);
		picture = new JLabel();
		picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
		picture.setHorizontalAlignment(JLabel.CENTER);
		picture.addMouseListener(this);
		picture.addMouseWheelListener(this);

		pictureScrollPane = new JScrollPane(picture);

		// Create a split pane with the two scroll panes in it.
		splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listScrollPane,	pictureScrollPane);
		splitPane.setOneTouchExpandable(true);
		splitPane.setDividerLocation(190);
		splitPane.setDividerSize(8);

		updateLabel("ricette.jpg", false, false);
	}

	public void clear() {
		rootNode.removeAllChildren();
		treeModel.reload();
	}

	public void loadTree() {
		createNodes(new File(RICETTE_DIR), this.rootNode);
	}
	
	public void showImageFromTree(TreePath path)
	{
		Object[] paths = path.getPath();
		if (path.getParentPath() == null)
		{
			System.out.println("Root node choosen");
			updateLabel(null, false, true);
		}
		else
		{
			File file = ((NodeBean) ((javax.swing.tree.DefaultMutableTreeNode) paths[paths.length - 1]).getUserObject()).getFile();
			if (file.isDirectory())
			{
				System.out.println("Directory selected " + file.getPath());
				updateLabel(null, false, true);
			}
			else
			{
				System.out.println("File selected " + file.getPath());
				updateLabel(file.getPath(), false, true);
			}
		}		
	}

	private void createNodes(File fileIn, DefaultMutableTreeNode top) {
		DefaultMutableTreeNode category = null;
		DefaultMutableTreeNode book = null;

		if (!fileIn.exists())
			return;
		FilenameFilter filenameFilter = new FilenameFilter() {

			public boolean accept(File dir, String name) {
				if (name.endsWith(".db"))
					return false;
				return true;
			}
		};
		File[] files = dirListByAscendingName(fileIn, filenameFilter);

		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				File[] filestemp = dirListByAscendingName(files[i], filenameFilter);
				if (filestemp!= null && allImagesAreFake(filestemp) == true)
				{
					for (int jk = 0; jk < filestemp.length; jk++) {
						String name = files[i].getName();
						if (filestemp.length > 1)
							name = name + " ("+(jk+1)+ ")";
						System.out.println("################"+filestemp[jk].getName()+" renaming in ->"+name);
						book = new DefaultMutableTreeNode(new NodeBean(filestemp[jk],name));
						top.add(book);
					}
				}
				else
				{
					System.out.println("DIR = " + files[i].getName());
					category = new DefaultMutableTreeNode(new NodeBean(files[i], files[i].getName()));
					top.add(category);
					createNodes(files[i], category);
				}
			} else if (files[i].isFile()) {
				String fileName = files[i].getName();
				System.out.println("Ricetta = " + fileName);
				if (fileName.toLowerCase().startsWith("image") && fileIn.isDirectory())
					fileName = fileIn.getName();
				book = new DefaultMutableTreeNode(new NodeBean(files[i], fileName));
				top.add(book);
			}
		}

	}
	
	public JTree getTree() {
		return tree;
	}

	private boolean allImagesAreFake(File[] files) {
		boolean returnValue = true;
		for (int i = 0; i < files.length; i++) {
			if (!files[i].getName().toLowerCase().startsWith("image") && !files[i].getName().toLowerCase().startsWith("001"))
				returnValue = false;
		}
		return returnValue;
	} 

	@SuppressWarnings("unchecked")
	public static File[] dirListByAscendingName(File folder,
			FilenameFilter filenameFilter) {
		if (!folder.isDirectory()) {
			return null;
		}
		File files[] = folder.listFiles(filenameFilter);
		Arrays.sort(files, new Comparator() {
			public int compare(final Object o1, final Object o2) {
				return new String(((File) o1).getName().toLowerCase()).compareTo(new String(((File) o2).getName().toLowerCase()));
			}
		});
		return files;
	}
	
	protected void updateLabel(String name, boolean restImage, boolean resized) {
		updateLabel(name, restImage, resized, 0);
	}

	// Renders the selected image
	protected void updateLabel(String name, boolean restImage, boolean resized, int incrementDirection) {
		
		// Get the IMAGE
		ImageIcon icon = null;
		if (restImage)
			icon = (ImageIcon) picture.getIcon();
		else
		 icon = createImageIcon(name);
		
		// FULLSCREEN
		if (!resized)
			picture.setIcon(icon);
		else
		{
			// Mantiene le dimensioni originali dell'immagine
			Dimension dim = calculateImageSpace();
			int heightTmp = dim.getHeight() > icon.getIconHeight() ? icon.getIconHeight(): (int)dim.getHeight();
			int widthTmp = dim.getWidth() > icon.getIconWidth() ? icon.getIconWidth() : (int)dim.getWidth();
			if (incrementDirection != 0)
			{
				ImageIcon originalIcon = createImageIcon(name);
				System.out.println("Original dimension " + originalIcon.getIconHeight() + "," + originalIcon.getIconWidth());
				System.out.println("Viewable dimension " + icon.getIconHeight() + "," + icon.getIconWidth());
				double incrementDirectionDouble  = incrementDirection + 0.2;
				if (incrementDirectionDouble < 0)
					incrementDirectionDouble = incrementDirectionDouble * -1;
				
				int icrementedHeight = (int) (icon.getIconHeight()*incrementDirectionDouble);
				int incremetedWidth = (int) (icon.getIconWidth()*incrementDirectionDouble);
				
				if (icrementedHeight >0)
					heightTmp = icrementedHeight > originalIcon.getIconHeight() ? originalIcon.getIconHeight(): (int)icrementedHeight;
				
				if (incremetedWidth > 0)
					widthTmp = incremetedWidth > originalIcon.getIconWidth() ? originalIcon.getIconWidth() : (int)incremetedWidth;
				
				icon = originalIcon;
				System.out.println("Final dimension " + heightTmp + "," + widthTmp);
			}
			
			picture.setIcon(new ImageIcon(getScaledImage(icon.getImage(), widthTmp, heightTmp)));
		}
		
		if (icon != null) {
			picture.setText(null);
		} else {
			picture.setText("Image not found");
		}
	}

    public JScrollPane getPictureScrollPane() {
		return pictureScrollPane;
	}

	private Image getScaledImage(Image srcImg, int w, int h){
        BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = resizedImg.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(srcImg, 0, 0, w, h, null);
        g2.dispose();
        return resizedImg;
    }
    
	public JSplitPane getSplitPane() {
		return splitPane;
	}

	/** Returns an ImageIcon, or null if the path was invalid. */
	protected static ImageIcon createImageIcon(String path) {
        
		// Se si tratta di file allora lo mostra
		if (path != null && path.startsWith("."))
    		return new ImageIcon(path);
		// Se si tratta di una cartella o di un path che non sia un file allora mostra l'immagine di default
    	else
    	{
	    	java.net.URL imgURL = ScrollDemo.class.getResource("images/ricette.jpg");    	
	        if (imgURL != null) {
	        	return new ImageIcon(imgURL);
	        } else {
	            System.err.println("Couldn't find file: " + path);
	            return null;
	        }
    	}
	}

	/**
	 * Create the GUI and show it. For thread safety, this method should be
	 * invoked from the event-dispatching thread.
	 */
	private static void createAndShowGUI() {

		// Create and set up the window.
		final RicettarioViewer splitPaneDemo = new RicettarioViewer();
		(((BasicSplitPaneUI)splitPaneDemo.getSplitPane().getUI()).getDivider()).addComponentListener(new ComponentAdapter() {
		      public void componentMoved(ComponentEvent ce) 
		      { 
		    	  System.out.println("Moved");
					TreePath path = splitPaneDemo.getTree().getSelectionPath();
					if (path != null)
					{
						Object[] paths = path.getPath();
						File file = ((NodeBean) ((javax.swing.tree.DefaultMutableTreeNode) paths[paths.length - 1]).getUserObject()).getFile();
						System.out.println("File name = " + file.getName());
						if (!file.isDirectory())
							splitPaneDemo.updateLabel(file.getPath(), false, true);
						else
							splitPaneDemo.updateLabel(null, true, true);
					}		    	  
		      }
		    });
		
		final JFrame frame = new JFrame("SplitPaneDemo");
		frame.setTitle("Ricettario");
		frame.setIconImage(splitPaneDemo.createImageIcon("images/ricette.jpg").getImage());
		frame.addComponentListener(new ComponentListener() {
			
			public void componentShown(ComponentEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			public void componentResized(ComponentEvent e) {
				TreePath path = splitPaneDemo.getTree().getSelectionPath();
				if (path != null)
				{
					Object[] paths = path.getPath();
					File file = ((NodeBean) ((javax.swing.tree.DefaultMutableTreeNode) paths[paths.length - 1]).getUserObject()).getFile();
					System.out.println("File name = " + file.getName());
					if (!file.isDirectory())
						splitPaneDemo.updateLabel(file.getPath(), false, true);
					else
						splitPaneDemo.updateLabel(null, true, true);
				}				
			}
			
			public void componentMoved(ComponentEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			public void componentHidden(ComponentEvent e) {
				// TODO Auto-generated method stub
				
			}
		});
		
		frame.getContentPane().setLayout(new BorderLayout(0,0));
        JButton btnCarica = new JButton("Carica ricette");
		btnCarica.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				splitPaneDemo.clear();
				splitPaneDemo.loadTree();
			}
		});
		btnCarica.setToolTipText("Effettua la scansione delle ricette");

		JButton btnEsci = new JButton("Esci");
		btnEsci.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				frame.dispose();
			}
		});
		btnEsci.setToolTipText("Chiude l'applicazione");
		
		JLabel labelRicerca = new JLabel("Ricerca ricetta:");
		
		final JTextField ricercaField = new JTextField(10);
		ricercaField.setEditable(true);
		
		
		JButton btnRicerca = new JButton("Ricerca");
		btnRicerca.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				numMatchFind++;
				JTree tree = splitPaneDemo.getTree();

				if (!textToFind.equals(ricercaField.getText()))
				{
					System.out.println("Resetting find...");
					textToFind = ricercaField.getText();
					collapseAll(tree);
					numMatchFind = 1;
				}
				
				TreePath path = findByName(tree, textToFind, numMatchFind);
				if (path == null)
				{
					numMatchFind = 0;
					path = findByName(tree, ricercaField.getText(), numMatchFind);
					if (path == null)
						 splitPaneDemo.showImageFromTree(tree.getSelectionPath());
					
					final JDialog dialog = new JDialog(frame, "Attenzione", true);
					JLabel msgDialog = new JLabel("Nessun risultato trovato!");
					msgDialog.setForeground(Color.RED);
					JButton btnClose = new JButton("Chiudi");
					btnClose.setSize(30, 30);
					btnClose.addActionListener(new ActionListener() {
						
						@Override
						public void actionPerformed(ActionEvent e) {
							dialog.dispose();
						}
					});
					ImageIcon warning = null;
					java.net.URL imgURL = ScrollDemo.class.getResource("images/warning.png");    	
			        if (imgURL != null) 
			        	warning = new ImageIcon(imgURL);					
					dialog.setSize(200, 100);
					dialog.setLocationRelativeTo(frame);
					dialog.setResizable(false);
					dialog.setLayout(new BorderLayout());
					dialog.add(msgDialog, BorderLayout.CENTER);
					dialog.add(btnClose, BorderLayout.SOUTH);
					dialog.setIconImage(warning.getImage());
					dialog.setVisible(true);					
				}
				else
				{
		            tree.scrollPathToVisible(path);
		            tree.setSelectionPath(path);
		            splitPaneDemo.showImageFromTree(path);
					tree.expandPath(path.getParentPath());
					System.out.println("FINALE " + path);		            
				}

			}
		});
		btnRicerca.setToolTipText("Ricerca una ricetta");
		
		JButton helpBtn = new JButton("Aiuto");
		helpBtn.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				final JDialog dialog = new JDialog(frame, "Aiuto in linea", true);
				JLabel msgDialog = new JLabel("<html><body><P><FONT COLOR=\"#2a00ff\"><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=3 STYLE=\"font-size: 13pt\">Il seguente aiuto spiega le funzionalità  di base del programma.</FONT></FONT></FONT></P>" +
						"<P><FONT COLOR=\"#2a00ff\"><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=3 STYLE=\"font-size: 11pt\"><br><B>RICERCA</B></FONT></FONT></FONT></P>" +
						"<P STYLE=\"font-weight: normal\"><FONT COLOR=\"#2a00ff\"><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=3 STYLE=\"font-size: 11pt\">"+
						"<I>La ricerca di un contenuto viene effettuata tramite l'inserimento della parola da ricercare e poi tramite la pressione del pulsante ricerca.</I></FONT></FONT></FONT></P> " +
						"<P STYLE=\"font-weight: normal\"><FONT COLOR=\"#2a00ff\"><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=3 STYLE=\"font-size: 11pt\"><I>Ad ogni successiva pressione del pulsante verrà ricercata la successiva parola." +
						"Quando non viene più trovata nessuna occorrenza alla compare un messaggio che segnalerà la fine della ricerca dei contenuti. Alla successiva pressione di ricerca il programma comincerà di nuovo la ricerca da capo. " +
						"Ad ogni inserimenbto di parola nuova da ricerca la ricerca comincerà dall'inizio.</I></FONT></FONT></FONT></P>" +
						"<P STYLE=\"font-weight: normal\"><BR><BR></P><P STYLE=\"font-style: normal\"><FONT COLOR=\"#2a00ff\"><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=3 STYLE=\"font-size: 11pt\"><B>GESTIONE IMMAGINI</B></FONT></FONT></FONT></P>" +
						"<P STYLE=\"font-weight: normal\"><FONT COLOR=\"#2a00ff\"><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2 STYLE=\"font-size: 11pt\"><I>Alla selezione della voce nell'albero verrà visualizzata sulla parte di" +
						" destra l'immagine corrispondente adattandosi allo spazio visibile. </I></FONT></FONT></FONT></P><P STYLE=\"font-weight: normal\"><FONT COLOR=\"#2a00ff\"><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=3 STYLE=\"font-size: 11pt\"><I>Con la pressione del tasto sinistro del mouse l'immagine si espande alla"+
						" sue massime dimensioni.</I></FONT></FONT></FONT></P><P STYLE=\"font-weight: normal\"><FONT COLOR=\"#2a00ff\"><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=3 STYLE=\"font-size: 11pt\"><I>Con la pressione del tasto destro del mouse l'immagine si adatta allo " +
						" spazio visibile.</I></FONT></FONT></FONT></P><P STYLE=\"font-weight: normal\"><FONT COLOR=\"#2a00ff\"><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=3 STYLE=\"font-size: 11pt\"><I>Con il movimento della rotella del mouse l'immagine si ingrandisce o si " +
						" riduce a seconda della rotazione della rotella. Al ridimensionamento della finestra principale o del divisore l'immagine torna a occpuare sempre tutto lo spazio visibile.</I></FONT></FONT></FONT></P>" +
						"</body></html>");
				msgDialog.setForeground(Color.BLUE);
				JButton btnClose = new JButton("<html><body><b>Chiudi</b></body></html>");
				btnClose.setSize(30, 30);
				btnClose.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent e) {
						dialog.dispose();
					}
				});
				dialog.setSize(450, 450);
				dialog.setLocationRelativeTo(frame);
				dialog.setResizable(true);
				dialog.setLayout(new BorderLayout());
				dialog.add(msgDialog, BorderLayout.NORTH);
				dialog.add(btnClose, BorderLayout.PAGE_END);
				dialog.setVisible(true);		
				
			}
		});

		JPanel panelBtn = new JPanel();
		panelBtn.setLayout(new FlowLayout(FlowLayout.LEFT));
		
		panelBtn.add(btnCarica);
		panelBtn.add(Box.createHorizontalStrut(37));
		panelBtn.add(labelRicerca);
		panelBtn.add(ricercaField);
		panelBtn.add(btnRicerca);
		panelBtn.add(Box.createHorizontalStrut(27));
		panelBtn.add(helpBtn);
		panelBtn.add(Box.createHorizontalStrut(57));		
		panelBtn.add(btnEsci);
		
		frame.getContentPane().add(panelBtn, BorderLayout.NORTH);
		frame.getContentPane().add(splitPaneDemo.getSplitPane(), BorderLayout.CENTER);

	    Toolkit t = Toolkit.getDefaultToolkit();
	    Dimension d = t.getScreenSize();
		frame.setSize(d);
		
		// Display the window.
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		
		frame.pack();
		frame.setVisible(true);

	    System.out.println("Screen size: "+d.width+", "+d.height);
	    System.out.println("Screen resolution: "+t.getScreenResolution());		
		
	}

	private static void collapseAll(JTree tree) {
	    int row = tree.getRowCount() - 1;
	    while (row >= 0) {
		      tree.collapseRow(row);
		      row--;
	      }
	}
	// Finds the path in tree as specified by the array of names. The names array is a
	// sequence of names where names[0] is the root and names[i] is a child of names[i-1].
	// Comparison is done using String.equals(). Returns null if not found.
	public static TreePath findByName(JTree tree, String names, int numMatch) {
	    TreeNode root = (TreeNode)tree.getModel().getRoot();
	    matchFound = 0;
	    return find2(tree, new TreePath(root), names, numMatch);
	}
	
	private static int matchFound = 0;
	private static int numMatchFind = 0;
	private static String textToFind = "";
	
	private static TreePath find2(JTree tree, TreePath parent, Object nodes, int matchDesired) {
	    TreeNode node = (TreeNode)parent.getLastPathComponent();
	    Object o = node;

	    // If equal, go down the branch
	    if (o.toString().toLowerCase().contains(nodes.toString().toLowerCase()))
	    {
	    	if (node.isLeaf())
	    	{
		    	matchFound++;
		    	System.out.println("FOUND MATCH FOR " + o + ", MATCH# " + matchFound + ", matchDesired " + matchDesired);
		    	if (matchFound==matchDesired)
		    		return parent;
	    	}
	    }
        // Traverse children
        if (node.getChildCount() >= 0) {
            for (Enumeration e=node.children(); e.hasMoreElements(); ) {
                TreeNode n = (TreeNode)e.nextElement();
                TreePath path = parent.pathByAddingChild(n);
                TreePath result = find2(tree, path, nodes, matchDesired);
                // Found a match
                if (result != null) {
                	System.out.println("FINDING RESULT " + result);
                    return result;
                }
            }
        }


	    // No match at this branch
	    return null;
	}

	public static void main(String[] args) {
		// Schedule a job for the event-dispatching thread:
		// creating and showing this application's GUI.
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});
	}

}
